package com.m3958.firstgwt.server.servlet;

import java.io.File;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Singleton;
import com.m3958.firstgwt.client.utils.StringUtils;
import com.m3958.firstgwt.server.dao.AssetDao;
import com.m3958.firstgwt.server.model.Asset;
import com.m3958.firstgwt.server.service.AppUtilService;
import com.m3958.firstgwt.server.service.FilePathService;
import com.m3958.firstgwt.server.service.FourOFourService;
import com.m3958.firstgwt.server.service.SiteConfigService;


@Singleton
public class AssetFeedServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	@Inject
	Injector injector;
	
	@Inject
	protected FilePathService fps;
	
	@Inject
	private AppUtilService aus;
	
	@Inject
	private SiteConfigService scs;
	
	private static Pattern p = Pattern.compile("^/asset/(\\d+)\\.?(\\d+x\\d+)?\\.?.*");
	//qw/800x600>m 128x128>s 48x48>t/;
	@Override
	public void doGet(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		
		String etag = req.getHeader("If-None-Match");
		if(etag != null){
    		res.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
    		return;
		}
		
		String assetIdStr = req.getParameter("assetId");
		String size = req.getParameter("size");
		
		if(assetIdStr == null || assetIdStr.isEmpty()){
			String uri = req.getRequestURI();
			Matcher m = p.matcher(uri);
			boolean b = m.matches();
			if(b){
				assetIdStr = m.group(1);
				size = m.group(2);
			}else{
				res.setStatus(HttpServletResponse.SC_NO_CONTENT);
				return;
			}
		}

		int assetId = Integer.parseInt(assetIdStr);
		AssetDao dao = injector.getInstance(AssetDao.class);
		Asset a = dao.find(assetId);
		if(a == null){
			res.setStatus(HttpServletResponse.SC_NO_CONTENT);
			return;
		}
		
		File bf = new File(scs.getAssetSavePath());
		File f;
		if(size == null || size.isEmpty()){
			f = new File(bf,a.getFilePath());
			size = "";
		}else{
			f = new File(bf,StringUtils.getFileNameAppend(a.getFilePath(), size));
			if(!f.exists()){
				f = new File(bf,a.getFilePath());
			}
		}
		
		if(!f.exists()){
			injector.getInstance(FourOFourService.class).send404();
			return;
		}
		aus.sendAsset(req, res, f, a.getMimeType(),a,size);
	}
}
